﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Animation;
using System.Collections.Generic;

using SBPweb.Forge.Contracts.Events;
using SBPweb.Forge.Contracts.Extensibility;

using SBPweb.Forge.Controls.Silverlight.Utilities;

using SBPweb.Communication.Shared.Library;
using SBPweb.Communication.Shared.Library.Contacts;
using SBPweb.Communication.Shared.Library.Conversations;

using SBPweb.Communication.Client.Library.Xmpp;
using SBPweb.Communication.Client.Library.Xmpp.Configuration;

using SBPweb.Communication.Client.Controls.Xmpp.Conversations;

using SBPweb.Communication.Client.Controls.Xmpp;

using SBPweb.PROvibe.Presentation.Client.Controls.Animation;
using SBPweb.PROvibe.Presentation.Client.Controls.Containers;

namespace SBPweb.PROvibe.Modules.Client.Communication.Xmpp.Controls
{

    public partial class MessengerMainPanel : UserControlBase
    {

        #region Private fields

        private bool isFlewnOut = true;
        private bool isLeanedIn = false;
        private bool isFlyingOut = false;
        private bool isLeaningIn = false;
        private bool isFrozen = false;
        private Login loginWindow;

        #endregion

        #region Constructor logic

        public MessengerMainPanel()
        {
            if (Application.Current is IExtendable)
            {
                (Application.Current as IExtendable).Put<MessengerBase>("Messenger", new Messenger());
                Messenger.Initialized += new EventHandler(messenger_Initialized);
                Messenger.Connections.Connecting += new EventHandler(messenger_Connections_Connecting);
                Messenger.Connections.Connected += new EventHandler(messenger_Connections_Connected);
                Messenger.Connections.Disconnecting += new EventHandler<CancelEventArgs>(messenger_Connections_Disconnecting);
                Messenger.Connections.Disconnected += new EventHandler(messenger_Connections_Disconnected);
                Messenger.Conversations.ConversationOpened += new EventHandler<SBPweb.Communication.Shared.Library.Conversations.ConversationEventArgs>(Conversations_ConversationOpened);
                (Messenger.Configurations as ConfigurationManager).Parameters = Application.Current.Host.InitParams;
            }
            InitializeComponent();

            if (Application.Current is IExtendable)
            {
                Messenger.Initialize();
            }
            LeanIn();
        }

        #endregion

        #region Property accessors

        public bool IsFlewnOut
        {
            get
            {
                return isFlewnOut;
            }
        }

        public bool IsLeanedIn
        {
            get
            {
                return isLeanedIn;
            }
        }

        public override MessengerBase Messenger
        {
            get
            {
                return base.Messenger;
            }
        }

        #endregion
        
        #region Methods

        #region Messenger

        private void messenger_Initialized(object sender, EventArgs e)
        {
            loginWindow = new Login();
            loginWindow.Title = string.Format("Login with XMPP Messenger to {0}", Messenger.Connections.Configuration.Server);
            loginWindow.Closed += new EventHandler(login_Closed);
            loginWindow.DialogResult = null;
            loginWindow.Show();
        }

        private void login_Closed(object sender, EventArgs e)
        {
            if (loginWindow.DialogResult.HasValue && loginWindow.DialogResult.Value)
            {
                Messenger.Connections.Connect(loginWindow.UserName, loginWindow.Password);
            }
        }

        private void messenger_Connections_Disconnecting(object sender, CancelEventArgs e)
        {
            Dispatcher.BeginInvoke(delegate()
            {
                DisableMessengerControls();
            });
        }

        private void messenger_Connections_Disconnected(object sender, EventArgs e)
        {
            Dispatcher.BeginInvoke(delegate()
            {
                DisableMessengerControls();
            });
        }

        private void messenger_Connections_Connecting(object sender, EventArgs e)
        {
            Dispatcher.BeginInvoke(delegate()
            {
                DisableMessengerControls();
            });
        }

        private void messenger_Connections_Connected(object sender, EventArgs e)
        {
            Dispatcher.BeginInvoke(delegate()
            {
                EnableMessengerControls();
            });
        }

        private void Conversations_ConversationOpened(object sender, ConversationEventArgs e)
        {
            Dispatcher.BeginInvoke(delegate()
            {
                ConversationWindow cw = new ConversationWindow(e.Conversation);
                cw.Show();
            });
        }

        #endregion

        #region UI handlers

        private void MainPanel_MouseEnter(object sender, MouseEventArgs e)
        {
            if (isFlyingOut || isFlewnOut || isFrozen)
            {
                return;
            }
            FlyOut();
        }

        private void MainPanel_MouseLeave(object sender, MouseEventArgs e)
        {
            if (isLeaningIn || isLeanedIn || isFrozen)
            {
                return;
            }
            LeanIn();
        }

        private void MessengerKnob_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (!Messenger.Connections.IsConnected)
            {
                loginWindow.DialogResult = null;
                loginWindow.Show();
            }
        }

        private void FlyOut()
        {
            isFlyingOut = true;
            isFlewnOut = false;
            Storyboard sb = new Storyboard();
            sb.Completed += new EventHandler(sbFlyOut_Completed);
            DoubleAnimation anim = ThicknessAnimation.Create(gridMain, Control.MarginProperty, new Duration(TimeSpan.FromSeconds(0.25)), new Thickness(242, 0, 0, 0), new Thickness(0, 0, 0, 0)) as DoubleAnimation;
            PowerEase ease = new PowerEase();
            ease.EasingMode = EasingMode.EaseIn;
            anim.EasingFunction = ease;
            sb.Children.Add(anim);
            sb.Begin();
        }

        private void LeanIn()
        {
            isLeaningIn = true;
            isLeanedIn = false;
            Storyboard sb = new Storyboard();
            sb.Completed += new EventHandler(sbLeanIn_Completed);
            DoubleAnimation anim = ThicknessAnimation.Create(gridMain, Control.MarginProperty, new Duration(TimeSpan.FromSeconds(0.5)), new Thickness(0, 0, 0, 0), new Thickness(242, 0, 0, 0)) as DoubleAnimation;
            PowerEase ease = new PowerEase();
            ease.EasingMode = EasingMode.EaseOut;
            anim.EasingFunction = ease;
            sb.Children.Add(anim);
            sb.Begin();
        }

        private void DisableMessengerControls()
        {
            this.xmppConnectionsView.IsEnabled = false;
            this.xmppContactsView.IsEnabled = false;
        }

        private void EnableMessengerControls()
        {
            this.xmppConnectionsView.IsEnabled = true;
            this.xmppContactsView.IsEnabled = true;
        }

        private void sbFlyOut_Completed(object sender, EventArgs e)
        {
            isFlyingOut = false;
            isFlewnOut = true;
            isLeanedIn = false;
            isLeaningIn = false;
        }

        private void sbLeanIn_Completed(object sender, EventArgs e)
        {
            isFlyingOut = false;
            isFlewnOut = false;
            isLeaningIn = false;
            isLeanedIn = true;
        }

        private void xmppConnectionsView_PresenceSelectionOpened(object sender, EventArgs e)
        {
            isFrozen = true;
        }

        private void xmppConnectionsView_PresenceSelectionClosed(object sender, EventArgs e)
        {
            isFrozen = false;
        }

        private void xmppContactsView_ItemSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            foreach(ContactBase cb in e.AddedItems)
            {
                xmppToolBar.ManageableContacts.Add(cb);
            }
            foreach (ContactBase cb in e.RemovedItems)
            {
                xmppToolBar.ManageableContacts.Remove(cb);
            }
        }

        #endregion

        #endregion


    }

}